/*
	钱包创建工具

*/

package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"

	"github.com/hyperledger/fabric-sdk-go/pkg/gateway"
)

func help() {
	fmt.Println("./wallet <wallet-path> <private key path>")
}

func main() {
	log.Println("============ begin generate wallet user ============")
	if len(os.Args) < 3 {
		help()
		os.Exit(0)
	}
	wallet, err := gateway.NewFileSystemWallet(os.Args[1])
	if err != nil {
		log.Fatalf("Failed to create wallet: %v", err)
	}

	err = populateWallet(wallet, os.Args[2])
	if err != nil {
		log.Fatalf("Failed to populate wallet contents: %v", err)
	}

	log.Println("============ generate wallet user end ============")
}

func populateWallet(wallet *gateway.Wallet, rootPath string) error {
	log.Println("============ Populating wallet ============")
	credPath := filepath.Join(
		rootPath,
		"organizations",
		"peerOrganizations",
		"org1.example.com",
		"users",
		"User1@org1.example.com",
		"msp",
	)

	certPath := filepath.Join(credPath, "signcerts", "User1@org1.example.com-cert.pem")
	// read the certificate pem
	cert, err := ioutil.ReadFile(filepath.Clean(certPath))
	if err != nil {
		return err
	}

	keyDir := filepath.Join(credPath, "keystore")
	// there's a single file in this dir containing the private key
	files, err := ioutil.ReadDir(keyDir)
	if err != nil {
		return err
	}
	if len(files) != 1 {
		return fmt.Errorf("keystore folder should have contain one file")
	}
	keyPath := filepath.Join(keyDir, files[0].Name())
	key, err := ioutil.ReadFile(filepath.Clean(keyPath))
	if err != nil {
		return err
	}

	identity := gateway.NewX509Identity("Org1MSP", string(cert), string(key))

	return wallet.Put("appUser", identity)
}
